package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * 515. 在每个树行中找最大值
 * 剑指 Offer II 044. 二叉树每层的最大值
 *
 * @Author liw
 * @Date 2021/5/11 14:23
 * @Version 1.0
 */
public class LargestValues {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> a = new ArrayDeque<>();
        Queue<TreeNode> b = new ArrayDeque<>();
        a.add(root);
        while (!a.isEmpty()) {
            int max = Integer.MIN_VALUE;
            while (!a.isEmpty()) {
                TreeNode poll = a.poll();
                max = Math.max(max, poll.val);
                if (poll.left != null) {
                    b.add(poll.left);
                }
                if (poll.right != null) {
                    b.add(poll.right);
                }
            }
            list.add(max);
            a = b;
            b = new ArrayDeque<>();
        }
        return list;
    }
}
